package com.longe.netty.decoderAndEncoder;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;

/**
 * Netty聊天服务
 */
public class NettyServer {

    public static void main(String[] args) {

        EventLoopGroup bossGroup = new NioEventLoopGroup(1);
        EventLoopGroup workerGroup = new NioEventLoopGroup();

        try {
            //创建服务器端的启动对象
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            //设置配置
            serverBootstrap.group(bossGroup, workerGroup) //设置两个线程组
                    .channel(NioServerSocketChannel.class) //使用NioServerSocketChannel作为服务端的通道实现
                    .option(ChannelOption.SO_BACKLOG, 128) //设置等待连接
                    .childOption(ChannelOption.SO_KEEPALIVE, true) //保持活动连接状态
                    //为workerGroup 的 EventLoop 对应的管道设置处理器
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) {
                            //为pipeline添加handler
                            ChannelPipeline pipeline = ch.pipeline();
                            //为pipeline添加解码器handler
                            pipeline.addLast(new MyByteToLongDecoder());
                            //为pipeline添加编码器handler
                            pipeline.addLast(new MyLongToByteEncoder());
                            //为pipeline添加自己的业务handler
                            pipeline.addLast(new NettyServerHandler());
                        }
                    });

            //绑定端口并同步
            ChannelFuture channelFuture = serverBootstrap.bind(9999).sync();

            System.err.println("Netty 服务器启动");
            //对关闭通道进行监听
            channelFuture.channel().closeFuture().sync();

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }

    }
}